<?php

namespace app\modules\weixin\controllers;

use app\common\services\HttpClient;
use app\common\services\StaticServices;
use app\models\Member;
use app\modules\weixin\controllers\common\BaseController;
use yii\base\Exception;
use yii\helpers\Url;
use yii\web\Response;

class OauthController extends BaseController
{
    public function actionBind()
    {
        $scope = \Yii::$app->request->get('scope', 'snsapi_base');
        $appid = \Yii::$app->params['weixin']['appid'];
        $redirect_url = Url::to('/oauth/callback');
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_url}&response_type=code&scope={$scope}&state=#wechat_redirect ";
        return $this->redirect($url);
    }

    public function actionCallback()
    {
        $code = \Yii::$app->request->get('code', '');
        if (!$code) {
            return false;
        }
        //通过code获取网页授权的access_token
        $appid = \Yii::$app->params['weixin']['appid'];
        $secret = \Yii::$app->params['weixin']['app_secret'];
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
        $result = HttpClient::get($url);
        $ret = @json_decode($result, true);
        $ret_token = isset($ret['access_token']) ? $ret['access_token'] : '';
        if (!$ret_token) {
            return false;
        }
        $openid = isset($ret['openid']) ? $ret['openid'] : '';
        $scope = isset($ret['scope']) ? $ret['scope'] : '';

        //获取用户具体信息
        $weixin_user_info = [];
        if ($scope == 'snsapi_userinfo') {
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$ret_token}&openid={$openid}&lang=zh_CN";
            $wechat_user_info = HttpClient::get($url);
            $weixin_user_info = @json_decode($wechat_user_info, true);
        }

        \Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            //判断用户是否存在
            $member_info = Member::find()->where(['open_id' => $openid])->one();
            if (!$member_info) {
                $member_info = new Member();
                $member_info->open_id = $openid;
                $member_info->nickname = $weixin_user_info['nickname'];
                $member_info->sex = $weixin_user_info['sex'];
                $member_info->city = $weixin_user_info['city'];
                $member_info->province = $weixin_user_info['province'];
                $member_info->country = $weixin_user_info['country'];
                $member_info->avatar = $weixin_user_info['headimgurl'];
                $member_info->ip = StaticServices::getIP();
                $member_info->unionid = $weixin_user_info['unionid'];
                $member_info->lastlogin_time = time();
                $member_info->create_time = time();
                $member_info->save(0);
            } else {
                $member_info->lastlogin_time = time();
                $member_info->save(0);
            }
            return ['code' => 200, 'user_info' => $member_info];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }

//        \Yii::$app->session->set('user_info', $member_info);
//        return $this->redirect(UrlServices::buildMUrl('/lan-ting/index', ['share_id' => $share_id]));
//        return $this->redirect(Url::to(['/member/index']));
    }
}
